<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of soaUsers
 *
 * @author dxx
 */

namespace app\common\model\jooj_member;

class MemberIndex extends Base {

    protected $base_table = 'jj_member_index';
    protected $table = 'jj_member_index';
    protected $connection = ['database' => 'jooj_member'];

    public function __construct($data = []) {
        if (!is_array($data)) {
            $this->table = $this->base_table . '_' . $data;
        }
        $data = is_array($data) ? $data : [];
        parent::__construct($data);
    }

    /**
     * 会员注册(微信)
     * @param type $params
     * @return type
     */
    public function addMemberIndex($params = [],$returnArr = false) {

        $IndexData = [];
        $IndexData['name'] = isset($params['name']) ? $params['name'] : null;
        $IndexData['gender'] = isset($params['gender']) ? intval($params['gender']) : null;
        $IndexData['birthday'] = isset($params['birthday']) ? $params['birthday'] : null;
        $IndexData['header_img'] = isset($params['header_img']) ? $params['header_img'] : null;
        $IndexData['come_from'] = isset($params['come_from']) ? $params['come_from'] : null;
        $IndexData['mp_id'] = isset($params['mp_id']) ? $params['mp_id'] : null;
        $IndexData['account_code'] = isset($params['account_code']) ? $params['account_code'] : null;
        $IndexData['wx_union_id'] = isset($params['wx_union_id']) ? $params['wx_union_id'] : null;
        $IndexData['mobile'] = isset($params['mobile'])?$params['mobile']:null;
        $IndexData['cardno'] = isset($params['cardno'])?$params['cardno']:null;
        $IndexData['mobile_status'] = isset($params['mobile_status'])?$params['mobile_status']:2;
        $IndexData['add_ts'] = time();
        $IndexData['last_ts'] = time();
        $IndexData['jj_uni_id'] = uniqid();

        $IndexData = array_filter($IndexData);
        
        if($returnArr){
            $memberCode = $this->setTable($this->table)->insertGetId($IndexData);
            $IndexData['member_code'] = $memberCode;
            return $IndexData;
        }else{
            return $this->setTable($this->table)->insertGetId($IndexData);
        }

         
    }

    /**
     * 通过memberCode修改vipId
     */
    public function updateVipIdByMemberCode($memberCode, $vipId) {
        $res = $this->where(['member_code' => $memberCode])->update(['vip_id' => $vipId]);
        if ($res === false) {
            return false;
        }
        return true;
    }

    /**
     * 会员注册(acrm同步)
     * @param type $params
     * @return type
     */
    public function syncMemberIndex($params = []) {

        $IndexData = [];
        $IndexData['cardno'] = isset($params['card_no']) ? $params['card_no'] : null;
        $IndexData['card_lev'] = isset($params['card_lev']) ? intval($params['card_lev']) : null;
        $IndexData['name'] = isset($params['name']) ? $params['name'] : null;
        $IndexData['gender'] = isset($params['gender']) ? intval($params['gender']) : null;
        $IndexData['birthday'] = isset($params['birthday']) ? $params['birthday'] :null;
        $IndexData['account_code'] = isset($params['openid']) ? $params['openid'] : null;
        $IndexData['mobile'] = isset($params['mobile']) ? $params['mobile'] : null;
        $IndexData['mp_id'] = isset($params['mp_id']) ? intval($params['mp_id']) : null;
        $IndexData['add_ts'] = time();
        $IndexData['last_ts'] = time();
        $IndexData['jj_uni_id'] = uniqid();

        $IndexData = array_filter($IndexData);

        return $this->setTable($this->table)->insertGetId($IndexData);
    }

    /**
     * 根据memberCodeArr去更新字段
     * @param type $field
     * @param type $value
     * @param type $memberCodeArr
     */
    public function updateValue($field, $value, $memberCodeArr) {
        
        if (empty($value) && ($field != 'account_code')) {
            return true;
        }
        
        //首先判断哪条记录
        $memberCodeString = implode(',', $memberCodeArr);
        $where = "member_code in ($memberCodeString) and $field <> '' and $field <> '0' and $field is not null";

        $single = $this->setTable($this->table)->where($where)
                        ->field('member_code')->find();

        $member_code = $single['member_code'];
        if (empty($member_code)) {
            $member_code = reset($memberCodeArr);
        }
        
        //把其它的逻辑清空
        $this->setTable($this->table)->where(['member_code' => ['in',$memberCodeArr]])->update(["{$field}" => null, 'last_ts' => time()]);
        //将数据更新进去
        $this->setTable($this->table)->where(['member_code' => $member_code])->update(["{$field}" => $value, 'last_ts' => time()]);
        
        return true;
    }

    /**
     * 通过memberCode或者vipId获取到memberCode的集合
     * @param type $memberCode
     * @param type $vipId
     * @return boolean/array
     */
    public function getMemberCodeArrByMemberCode($memberCode) {

        $where = ["member_code" => $memberCode];

        $singleMemberIndex = $this->where($where)->find();

        if (!$singleMemberIndex || empty($singleMemberIndex['jj_uni_id'])) {
            return false;
        }

        $jj_uni_id = $singleMemberIndex['jj_uni_id'];

        return $this->getMemberCodeArrByUniId($jj_uni_id);
    }

    /**
     * 通过jj_uni_id获取MemberCodeArr
     * @param type $jj_uni_id
     * @return type
     */
    public function getMemberCodeArrByUniId($jj_uni_id) {

        $MemberCodeArr = $this->setTable($this->table)->where(['jj_uni_id' => $jj_uni_id])->column('member_code');
        return $MemberCodeArr;
    }
    
    /**
     * 根据openId获取会员信息
     * @param type $openId
     * @return boolean
     */
    public function getMemberIndexByOpenId($openId, $field = "*") {

        $where = ['account_code' => $openId];

        $res = $this->setTable($this->table)->where($where)->field($field)->find();
        
        return $res;
    }
    

    /**
     * 根据openId获取会员信息
     * @param type $cardno
     * @param type $openId
     * @param type $mobile
     * @param type $field
     * @return type
     */
    public function getMemberIndexByAcrm($cardno, $openId, $mobile, $field = "*") {

        if (!empty($openId)) {
            $memberIndex = $this->setTable($this->table)->where(['account_code' => $openId])->find();
            if (!empty($memberIndex) && ($memberIndex['account_code'] != $openId)) {
                throw new \Exception('微信号已经存在！');
            }
        }

        if (!empty($mobile)) {
            $memberIndex = $this->setTable($this->table)->where(['mobile' => $mobile,'mobile_status'=>1])->find();
           
            if (!empty($memberIndex) && ($memberIndex['mobile'] != $mobile)) {
                throw new \Exception('手机号已经存在！');
            }
        }

        //如果openId或者mobile不为空，就得判断
        $where = ['cardno' => $cardno];

        $res = $this->setTable($this->table)->where($where)->field($field)->find();
        return $res;
    }

    /**
     * 为同步vip表的数据修改所用，请勿复用
     * @param type $vipId
     * @param type $params
     * @return boolean
     */
    public function updateMemberIndexSyncVip($vipId, $params) {
        if (empty($vipId)) {
            return true;
        }
        $data = [
            'name'     => isset($params['name']) ? $params['name'] : '',
            'gender'   => isset($params['gender']) ? $params['gender'] : 0,
            'birthday' => isset($params['birthday']) ? $params['birthday'] : '',
        ];

        //为了获取和memberIndex的数据同步保持一直，所以过滤掉空的数据
        $data = array_filter($data);

        if (empty($data)) {
            return false;
        }

        $data["last_ts"] = time();

        $res = $this->where(['vip_id' => $vipId])->update($data);
        if ($res === false) {
            return false;
        }
        return true;
    }

    public function addVIp($params) {
        $data['member_code'] = $params['member_code'];
        $data['name'] = $params['name'];
        $data['gender'] = $params['gender'];
        $data['birthday'] = $params['birthday'];
        $data['mobile'] = $params['mobile'];
        $data['mobile_status'] = $params['mobileStatus'];
        $data['come_from'] = $params['comeFrom'];
        $data['add_ts'] = time();
        $data['last_ts'] = time();
        $data['province'] = $params['province'];
        $data['city'] = $params['city'];
        $data['area'] = $params['area'];
        $data['cardno'] = $params['cardno'];
        $data['adress'] = $params['adress'];
        $data['zipcode'] = $params['zipcode'];
        $data['first_p'] = $params['first_p'];
        $data['first_store'] = $params['first_store'];
        $memberVipModel = new MemberVipModel();
        return $memberVipModel->registerVipId($data);
    }

    
    /**
     * 绑定手机号到openid
     * @param type $mobile
     * @param type $openId
     * @return type
     */
    private function bindMobile2OpenId($mobile,$openId){
        $data = [
            'mobile' => $mobile,
        ];
        $res = $this->where(['account_code' => $openId])->update($data);
        return $res === false ? false : true;
    }
    
    /**
     * 绑定openid到memberCode上
     * @param type $openId
     * @param type $memberCode
     * @return type
     */
    private function bindOpenId2MemberCode($openId,$memberCode){
        $data = [
            'account_code' => $openId,
        ];
        $res = $this->where(['member_code' => $memberCode])->update($data);
        return $res === false ? false : true;
    }
    
    /**
     * 绑定openid到手机号上
     * @param type $openId
     * @param type $mobile
     * @return type
     */
    private function bindOpenid2Mobile($openId,$mobile){
        $data = [
            'account_code' => $openId,
        ];
        $res = $this->where(['mobile' => $mobile])->update($data);
        return $res === false ? false : true;
    }

    /**
     * 把unionid绑定到手机号上
     * @param type $UnionId
     * @param type $mobile
     * @return type
     */
    private function bindUnionId2Mobile($UnionId,$mobile){
        $data = [
            'wx_union_id' => $UnionId,
        ];
        $res = $this->where(['mobile' => $mobile])->update($data);
        return $res === false ? false : true;
    }

    /**
     * 绑定数据
     * @param type $type mutil多行绑定，mobile手机绑定到微信那一行
     * @param type $mobile 
     * @param type $openId 
     * @param type $memberCode 要更改jj_uni_id那条的member_code
     * @param type $uni_id 要保留的jj_uni_id
     * @param type $wx_union_id 微信的unionId
     */
    public function bindMemberIndex($type = "mutil", $mobile='', $openId='', $memberCode='', $uni_id='',$wx_union_id='') {

        switch ($type){
            //1、把手机绑定到微信上
            case 'mobile':
            case 'mobile2openId':
                return $this->bindMobile2OpenId($mobile, $openId);
            //2、把微信openid绑定到memberCode上
            case 'openId':
            case 'openId2memberCode':
                return $this->bindOpenId2MemberCode($openId, $memberCode);
            //3、微信绑定到手机号上
            case 'openid2mobile':
                return $this->bindOpenid2Mobile($openId, $mobile);
            //4、unionId绑定到手机号上
            case 'unionId2mobile':
                return $this->bindUnionId2Mobile($wx_union_id, $mobile);
            case 'mutil':
                break;
            default :
                return false;
        }

        //5、mutil情况：把uni_id绑定到memberCode上
        //获取该跳memberCode的jj_uni_id
        $memberCodeOne = $this->where(['member_code'=>$memberCode])->find();
        if(empty($memberCodeOne)){
            return false;
        }
        
        $jJUniId = $memberCodeOne['jj_uni_id'];
        //更新一条记录的jj_uni_id
        $res = $this->where(['jj_uni_id' => $jJUniId])->update(['jj_uni_id' => $uni_id]);
        if ($res === false) {
            return false;
        }

        //2、同时做好对数据的处理
        $multiMemberIndex = $this->where(['jj_uni_id' => $uni_id])->order('header_img desc')->select();
        $vipMemberIndexCount = $this->where(['jj_uni_id' => $uni_id, 'mobile_status' => 1])->count();

        $memberCodeArr = [];

        foreach ($multiMemberIndex as $key => $item) {
            //赋值，为了返回下步清理memberIndexInfo的数据做打算
            $memberCodeArr[] = $item['member_code'];

            //所有行的数据，全部进行迁移
            $data = [];
            $data['old_mobile'] = $item['mobile'];
            $data['old_name'] = $item['name'];
            $data['old_gender'] = $item['gender'];
            $data['old_birthday'] = $item['birthday'];
            $data['old_vip_id'] = $item['vip_id'];
            $data['old_mobile_status'] = $item['mobile_status'];
            $data['old_card_lev'] = $item['card_lev'];
            $data['old_cardno'] = $item['cardno'];

            $data['mobile'] = null;
            $data['name'] = null;
            $data['gender'] = null;
            $data['birthday'] = null;
            $data['vip_id'] = null;
            $data['mobile_status'] = null;
            $data['card_lev'] = null;
            $data['cardno'] = null;

            //有vip的保留vip数据列
            if ($item['mobile_status'] == 1) {
                $data = [];
            }
            //没有vip的，以新绑定上的memberCode为准
            if ($vipMemberIndexCount == 0 && $item['member_code'] == $memberCode) {
                $data = [];
            }

            //因为已经按照头像倒叙了
            //只保留第一张即可
            if ($key > 0) {
                $data['old_header_img'] = $item['header_img'];
                $data['header_img'] = null;
            }

            if (empty($data)) {
                continue;
            }

            $data['last_ts'] = time();
            $res = $this->where(['member_code' => $item['member_code']])->update($data);
            if (!$res) {
                return false;
            }
        }

        return $memberCodeArr;
    }

    
    /**
     * 更新MemberIndex的数据
     * @param type $condition
     * @param type $params
     * @return type
     */
    public function updateMemberIndex($condition,$params){
        
        $iData = [];
        isset($params['name'])?$iData['name']=$params['name']:'';
        isset($params['gender'])?$iData['gender']=$params['gender']:'';
        isset($params['birthday'])?$iData['birthday']=$params['birthday']:'';
        isset($params['mobile'])?$iData['mobile']=$params['mobile']:'';
        isset($params['mobile_status'])?$iData['mobile_status']=$params['mobile_status']:'';
        isset($params['cardno'])?$iData['cardno']=$params['cardno']:'';
        isset($params['card_lev'])?$iData['card_lev']=$params['card_lev']:'';
        isset($params['header_img'])?$iData['cardno']=$params['header_img']:'';
        isset($params['last_ts'])?$iData['last_ts']=$params['last_ts']:'';
        isset($params['vip_id'])?$iData['vip_id']=$params['vip_id']:'';

        $res = $this->where($condition)->update($iData);
        
        return $res;
    }
    
    
    /**
     * 上述方法无法保存null这样的特殊处理
     * @param type $condition
     * @param type $params
     */
    public function saveMemberIndexNull($condition,$params){
        $res = $this->where($condition)->update($params);
        return $res;
    }



    /**
     * 获取一条信息
     * @param type $condition
     * @param type $field
     * @return type
     */
    public function getMemberInfoByCondition($condition, $field = '*',$order='') {
        
        $this->field($field);
        
        if($condition){
            $this->where($condition);
        }
        if($order){
            $this->order($order);
        }
        return $this->find();
    }

}
